// https://leetcode.cn/problems/path-sum/submissions/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

// dfs
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if (!root) return false;
        if (!root->left && !root->right) return root->val == targetSum;
        return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);
    }
};

// bfs
// 使用两个队列，分别存储将要遍历的节点，以及根节点到这些节点的路径和
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if (!root) return false;
        queue<TreeNode*> nodeQueue;
        nodeQueue.push(root);
        queue<int> numQueue;
        numQueue.push(root->val);
        while (!nodeQueue.empty()) {
            TreeNode* node = nodeQueue.front();
            nodeQueue.pop();
            int num = numQueue.front();
            numQueue.pop();
            if (!node->left && !node->right) {
                if (num == targetSum) return true;
                continue;
            }
            if (node->left) {
                nodeQueue.push(node->left);
                numQueue.push(num + node->left->val);
            }
            if (node->right) {
                nodeQueue.push(node->right);
                numQueue.push(num + node->right->val);
            }
        }
        return false;
    }
};